# go to http://api.census.gov/data/key_signup.html and get a key, then run the line below with your key. Don't push your key to github!
library(tidycensus)
#census_api_key("83e6682de7bfa24b9c6133fc65a0aea557d1f7b4")
library(tidycensus)
racevars <- c(White = "P005003",
Black = "P005004",
Asian = "P005006",
Hispanic = "P004003")
options(tigris_use_cache = TRUE)
erie <- get_decennial(geography = "block", variables = racevars,
state = "NY", county = "Erie County", geometry = TRUE,
summary_var = "P001001", cache_table=T)
## Getting data from the 2010 decennial Census
## Using Census Summary File 1
Crop the county-level data to c(xmin=-78.9,xmax=-78.85,ymin=42.888,ymax=42.92) to reduce the computational burdern. Feel free to enlarge this area if your computer is fast (or you are patient).
buffalo <- st_crop(erie, c(xmin=-78.9,xmax=-78.85,ymin=42.888,ymax=42.92))
## Warning: attribute variables are assumed to be spatially constant throughout all
## geometries
buffalo$variable = as.factor(buffalo$variable)
variable_vec = as.array(unique(buffalo$variable))
Write a foreach loop that does the following steps for each racial group in the variable column of the erie dataset and rbinds the results (e.g. .combine=rbind) into a single sf object. You may want to convert the variable column into a factor and use levels() or use unique(). filter the the data to include only one race at time use st_sample() to generate random points for each person that resided within each polygon. If you use a pipe (%>%), you will have to set size=.$value. The . indicates that the column comes from the dataset that was passed to the function. See here for details on how to use the . in a pipe. convert the points from st_sample() to spatial features with st_as_sf() mutate to add a column named variable that is set to the current racial group (from the foreach loop)
race_points <- foreach(i=1:4,.combine=rbind) %dopar%{
buffalo %>%
filter(variable==unique(buffalo$variable)[i]) %>%
st_sample(size=.$value) %>%
st_as_sf() %>%
mutate(variable = unique(buffalo$variable)[i])
}
mapview(race_points, zcol='variable', cex=1, alpha=0)